package net.entelijan.cobean.filesel;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class ExtensionsFileFilter implements IFileFilter {

    private List<String> extensions;

    private String description;

    public ExtensionsFileFilter() {
        super();
    }

    public ExtensionsFileFilter(String extention, String description) {
        super();
        ArrayList<String> exts = new ArrayList<String>();
        exts.add(extention);
        this.extensions = exts;
        this.description = description;
    }

    @Override
    public boolean accept(File f) {
        boolean re = false;
        if (f.isDirectory()) {
            re = true;
        } else {
            String fext = extractExtension(f);
            if (fext != null) {
                for (String ext : this.extensions) {
                    if (ext.equalsIgnoreCase(fext)) {
                        re = true;
                        break;
                    }
                }
            }
        }
        return re;
    }

    private String extractExtension(File f) {
        String re = null;
        String name = f.getName();
        int idx = name.lastIndexOf('.');
        if (idx >= 0) {
            re = name.substring(idx);
        }
        return re;
    }

    @Override
    public String getDescription() {
        if (this.description == null) {
            StringBuilder sb = new StringBuilder();
            int cnt = 0;
            for (String extension : extensions) {
                if (cnt++ > 0) {
                    sb.append(", ");
                }
                sb.append(extension);
            }
            this.description = sb.toString();
        }
        return this.description;
    }

    public List<String> getExtensions() {
        return extensions;
    }

    public void setExtensions(List<String> extensions) {
        this.extensions = extensions;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getExtension() {
        String re = null;
        if (this.extensions != null && this.extensions.size() > 1) {
            throw new IllegalStateException("More than one extension is defined for " + this);
        }
        if (this.extensions != null) {
            re = this.extensions.get(0);
        }
        return re;
    }

    public void setExtension(String extension) {
        ArrayList<String> exts = new ArrayList<String>();
        exts.add(extension);
        this.extensions = exts;
    }

}
